#include "reg51.h"

#define ADDR0 P1_0
#define ADDR1 P1_1
#define ADDR2 P1_2
#define ADDR3 P1_3
#define ENLED P1_4

#define KEY_IN_1 P2_4


// 数码管显示字符转换表
unsigned char __code LedChar[] = {
        0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92, 0x82, 0xF8,
        0x80, 0x90, 0x88, 0x83, 0xC6, 0xA1, 0x86, 0x8E
};

__bit keyState = 0;

int main() {
    unsigned char cnt = 0;
    unsigned char backup = 1;

    ENLED = 0;
    ADDR3 = 1;
    ADDR2 = 0;   // 选择数码管 1
    ADDR1 = 0;
    ADDR0 = 0;

    P2 = 0xF7;   // 拉低 KeyOut1
    P0 = LedChar[0];    // 默认显示 0

    EA = 1;      // 使能总中断
    TMOD = 0x01; // 设置 T0 为模式 1
    TH0 = 0xF8;  // 为 T0 赋初值，定时 2ms
    TL0 = 0xCD;

    ET0 = 1;     // 使能 T0 中断
    TR0 = 1;     // 启动 T0

    while (1) {
        if (backup != keyState) {
            if (backup == 1) {
                cnt++;
                cnt = cnt > 9 ? 0 : cnt;
                P0 = LedChar[cnt];
            }
            backup = keyState;
        }
    }
}

/**
 * 定时器 T0 中断服务函数
 */
void InterruptTimer0() __interrupt(1) {
    static unsigned char keyBuf = 0xFF;

    TH0 = 0xF8;  // 为 T0 赋初值，定时 2ms
    TL0 = 0xCD;

    keyBuf = (keyBuf << 1) | KEY_IN_1;
    if (keyBuf == 0xFF) {
        keyState = 1;
    } else if (keyBuf == 0x00) {
        keyState = 0;
    } else {

    }
}


